<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <p mv-text="msg"></p>
        <p mv-text="msg"></p>
        <hr>
        <p mv-text="info"></p>
        <p mv-text="info"></p>
    </div>

</body>
<script>
    
    function Watcher(){

    }
    Watcher.prototype._initDom=function($el,key){
        let sel=`[mv-text=${key}]`;
        // console.log(sel);
        this[key]=$el.querySelectorAll(sel);
        // console.log(this[key]);
    }
    Watcher.prototype.initData=function(_data){
        for(let key in _data){
            this.notify(key,_data[key]);
        }
    }
    Watcher.prototype.notify=function(key,value){
        // console.log(this[key]);//此时的this[key]为一个对象，要循环遍历对象里的值
        for(let i in this[key]){
            this[key][i].textContent=value;
        }
    }
    function Mvvm(obj){
        this._init(obj.el,obj.data);
    }
    Mvvm.prototype._init=function(el,data){
        this.$el=document.querySelector(el);
        // this.$el=document.getElementById(el);//不行
        // console.log(this.$el);
        this._data=data;
        // console.log(this._data);
        this._deeps(this._data);
    }
    Mvvm.prototype._deeps=function(_data){
        let watcher=new Watcher();
        for(let key in _data){
            watcher._initDom(this.$el,key);
            Object.defineProperty(this,key,{//让数据仓库中的属性变成全局属性
                get(){
                    console.log(key,"这是get方法!");
                    return _data[key];
                },
                set(nv){
                    console.log(key,"这是set方法!");
                    _data[key]=nv;
                    watcher.notify(key,_data[key]);
                    // console.log(Watcher.notify);
                }
            })
            // console.log(key);
        }
        watcher.initData(_data);
        // console.log(_data);
    }
    
    var mv=new Mvvm({
        el:"#app",
        data:{
            msg:"msg变量",
            info:"info变量"
        }
    })
</script>
</html>